package com.ruoyi.framework.security.filter.ykz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.api.request.OapiGettokenJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiRpcOauth2DingtalkAppTokenJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.response.OapiGettokenJsonResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiRpcOauth2DingtalkAppTokenJsonResponse;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.IntelligentPostClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class IntelligentPostService {

	private final static String GET_TOKEN = "/gettoken.json";
	private final static String GET_USER_INFO = "/rpc/oauth2/dingtalk_app_user.json";

	
	public final static String TOKEN_KEY = "ykz:auth:token";
	
	public final static String TICK_KEY = "ykz:auth:token";

	private static ExecutableClient executableClient;
	@Value("${ykz.auth.domainName}")
	public String domainName;
	@Value("${ykz.auth.protocol}")
	public String protocol;
	@Value("${ykz.auth.appKey}")
	public String appKey;
	@Value("${ykz.auth.appSecret}")
	public String appSecret;
	@Qualifier("stringRedisTemplate")
	@Autowired
	protected RedisTemplate<String, String> redisTemplate;

	@PostConstruct
	public void init() {
		executableClient = ExecutableClient.getInstance();
		// DomainName不同环境对应不同域名，渝快政使用下面示例, 政务外网需要查看接口必读完成配置
		executableClient.setDomainName(domainName);
		executableClient.setProtocal(protocol);
		// 应用App Key
		executableClient.setAccessKey(appKey);
		// 应用App Secret
		executableClient.setSecretKey(appSecret);
		executableClient.init();
	}

	public String getToken() {
		String accessToken = redisTemplate.opsForValue().get(TOKEN_KEY);
		if (!StringUtils.isEmpty(accessToken)) {
			if (log.isDebugEnabled()) {
				log.debug("缓存 accessToken 存在使用缓存 accessToken：{}", accessToken);
			}
			return accessToken;
		}
		// executableClient保证单例
		IntelligentPostClient intelligentGetClient = executableClient.newIntelligentPostClient(GET_TOKEN);
		OapiGettokenJsonRequest oapiGettokenJsonRequest = new OapiGettokenJsonRequest();
		// 获取结果
		OapiGettokenJsonResponse apiResult = intelligentGetClient.post(oapiGettokenJsonRequest);
		log.info("getToken:{}", apiResult);
		String dataStr = apiResult.getContent().getData();
		JSONObject data = JSON.parseObject(dataStr);
		accessToken = data.getString("accessToken");
		Integer expiresIn = data.getIntValue("expiresIn");
		// 设置redis缓存
        redisTemplate.opsForValue().set(TOKEN_KEY, accessToken, expiresIn, TimeUnit.SECONDS);
		return accessToken;
	}

	public OapiRpcAuth2UserInfo getUserInfo(String code, String token) {
		// executableClient保证单例
		IntelligentPostClient intelligentGetClient = executableClient.newIntelligentPostClient(GET_USER_INFO);
		OapiRpcOauth2DingtalkAppTokenJsonRequest oapiGetUserInfoReq = new OapiRpcOauth2DingtalkAppTokenJsonRequest();
		// 登录access_token
		oapiGetUserInfoReq.setAccess_token(token);
		// 临时授权码
		oapiGetUserInfoReq.setAuth_code(code);
		OapiRpcOauth2DingtalkAppTokenJsonResponse  apiResult = intelligentGetClient.post(oapiGetUserInfoReq);
		log.info("resp:\n" + apiResult.getContent());
		String dataStr = apiResult.getContent();
		String data = JSON.parseObject(dataStr).getJSONObject("content").getString("data");
		OapiRpcAuth2UserInfo userInfo = JSON.parseObject(data, OapiRpcAuth2UserInfo.class);
		log.info("getUserInfo:" + userInfo);
		
		return userInfo;
	}


}
